//
//  BTSession.m
//  ShovelBattle
//
//  Created by Jeoffrey Thirot on 14/03/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BTSession.h"

@implementation BTSession

@synthesize mSession, connectedPeer, mPeers;
@synthesize myName;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code
        mPeers = [[NSMutableArray alloc] init];
        myName = [NSString stringWithString:@"Player"];
    }
    return self;
}

#pragma mark - PeerPickerControllerDelegate stuff

/* Notifies delegate that a connection type was chosen by the user.
 */
- (void)peerPickerController:(GKPeerPickerController *)picker didSelectConnectionType:(GKPeerPickerConnectionType)type{
	if (type == GKPeerPickerConnectionTypeOnline) {
        picker.delegate = nil;
        [picker dismiss];
        [picker autorelease];
		// Implement your own internet user interface here.
    }
}

/* Notifies delegate that the connection type is requesting a GKSession object.
 
 You should return a valid GKSession object for use by the picker. If this method is not implemented or returns 'nil', a default GKSession is created on the delegate's behalf.
 */
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type{
    
	//UIApplication *app=[UIApplication sharedApplication];
	NSString *txt = myName;
    //NSDate *date = [NSDate date];
    //NSString *idSession = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]; 
    NSString *idSession = @"shovelBattle";
	GKSession* session = [[GKSession alloc] initWithSessionID:idSession displayName:txt sessionMode:GKSessionModePeer];
    [session autorelease];
    return session;
}

/* Notifies delegate that the peer was connected to a GKSession.
 */
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session{
    
	NSLog(@"Connected from %@",peerID);
    
	// Use a retaining property to take ownership of the session.
    self.mSession = session;
	// Assumes our object will also become the session's delegate.
    session.delegate = self;
    [session setDataReceiveHandler: self withContext:nil];
	// Remove the picker.
    /*picker.delegate = nil;
    [picker dismiss];
    [picker autorelease];
     */
	// Start your game.
}

- (void) sendData:(NSDictionary *)msg
{
    NSString *JSON = [msg JSONString];
	[mSession sendData:[JSON dataUsingEncoding: NSUTF8StringEncoding] toPeers:mPeers withDataMode:GKSendDataReliable error:nil];
}

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
    // Read the bytes in data and perform an application-specific action.
    
	NSString* aStr;
	aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSLog(@"Received Data from %@ :: %@", peer, aStr);
	
    // Create a notification for receive data
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    NSDictionary *result = [data objectFromJSONData];
    
    //NSDictionary *deserializedData = [aStr objectFromJSONData];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kSBReceiveDataFromSession object:nil userInfo:result];
    
}

/* Notifies delegate that the user cancelled the picker.
 */
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker{
    
}

#pragma mark GameSessionDelegate stuff

/* Indicates a state change for the given peer.
 */
- (void)session:(GKSession *)session 
           peer:(NSString *)peerID
 didChangeState:(GKPeerConnectionState)state
{
    
	switch (state)
    {
        case GKPeerStateAvailable:
        {
            if( !self.connectedPeer ) {
                [session connectToPeer:peerID withTimeout:120.];
            }
            break;
        }
        case GKPeerStateConnected:
		{
			//NSString *str = [NSString stringWithFormat:@"%@%@", @"Connected from peer ", peerID];
			//NSLog( @"%@", str );
			[mPeers addObject:peerID];
            self.connectedPeer = [peerID retain];
            NSLog(@"self.connectedPeer : %@, session peerID : %@",self.connectedPeer, [session peerID]);
            if( [self.connectedPeer compare:[session peerID]] > 0 ) {
                //Show l'utilisateur est connecte et attend
                NSLog(@"L'utilisateur est connecté et attend le second");
            } else {
                //Ici la double connection est bien
                NSLog(@"Les utilisateurs sont connectés. Ready for the next round !");
            }
            int num;
            if( self.connectedPeer > [session peerID] ) {
                num = 1;
            } else {
                num = 2;
            }
            NSDictionary *info = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:num] forKey:@"body"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kSBConnectedBTSession object:nil userInfo:info ];
            
			break;
		}
        case GKPeerStateDisconnected:
		{
			[mPeers removeObject:peerID];
            
			NSString *str = [NSString stringWithFormat:@"%@%@", @"DisConnected from peer ", peerID];
			
            if( self.connectedPeer == peerID ) {
                self.connectedPeer = nil;
                // Go return home for new connection
                [[NSNotificationCenter defaultCenter] postNotificationName:kSBDisconnectedSession object:nil];
            }
			NSLog( @"%@", str );
			break;
		}
        default:
            NSLog( @"state %d is not supported", state );
            break;
    }
}

- (void) session:(GKSession *)aSession didReceiveConnectionRequestFromPeer:(NSString *)peerID {
    NSError *error;
    if( self.connectedPeer ) {
        [aSession denyConnectionFromPeer:peerID];
    } else {
        [aSession acceptConnectionFromPeer:peerID error:&error];
    }
}

- (void) clearSession {
    NSLog(@"clear session :: %@", self.mSession);
    if( self.mSession ) {
        [self.mSession disconnectFromAllPeers];
        self.mSession.available = NO;
        self.mSession.delegate = nil;
        [self.mSession setDataReceiveHandler:nil withContext:nil];
        self.connectedPeer = nil;
        self.mSession = nil;
        NSLog(@"my session is clear !");
    }
}

- (void)dealloc {
	[mPeers release];
    [super dealloc];
}

@end
